import os
import pyradox.format
import pyradox.config
import pyradox.struct
import pyradox.txt
import pyradox.yml

# Lazy loading.
countries = None

def parseCountries():
    result = pyradox.struct.Tree()
    for filename, tree in pyradox.txt.parseDir(os.path.join(pyradox.config.basedirs['EU4'], 'history', 'countries')):
        tag, rawName = pyradox.format.splitFilename(filename)
        result.append(tag, tree)
    print('Loaded countries.')
    return result

def getCountries():
    """
    Get a copy of the country Tree, parsing if necessary.
    Maps tag -> country data.
    """
    global countries
    if countries is None: countries = parseCountries()
    return countries.deepCopy()

def getCountryName(tag):
    """
    Gets the name a country by its tag according to localization.
    """
    return pyradox.yml.getLocalization(tag, ['text', 'countries'])
